package com.dmall.graph.bfs;

import com.dmall.graph.Graph;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;

/**
 * @author: xiao1.wang
 * @date: 2022/6/19 15:30
 */
public class CC2 {
    private Graph G;
    private int[] visited;
    private int count = 0;

    public CC2(Graph G) {
        this.G = G;
        this.visited = new int[G.V()];
        Arrays.fill(this.visited, -1);
        for (int i = 0; i < G.V(); i++) {
            if (visited[i] == -1) {
                bfs(i, count);
                count ++;
            }
        }
    }

    private void bfs(int v, int ccid) {
        visited[v] = ccid;
        Queue<Integer> queue = new LinkedList<>();
        queue.offer(v);
        while (!queue.isEmpty()) {
            Integer cur = queue.poll();
            for (Integer w : G.adj(cur)) {
                if (visited[w] == -1) {
                    visited[w] = ccid;
                    queue.offer(w);
                }
            }
        }
    }

    public int count() {
        return count;
    }

    public boolean isConnectTo(int v, int w) {
        G.validateVertex(v);
        G.validateVertex(w);
        return visited[v] == visited[w];
    }

    public ArrayList<Integer>[] components() {
        ArrayList<Integer>[] res = new ArrayList[count];
        for (int i = 0; i < count; i++) {
            res[i] = new ArrayList<>();
        }
        for (int i = 0; i < visited.length; i++) {
            res[visited[i]].add(i);
        }
        return res;
    }

    public static void main(String[] args) {
        String filename = GraphBFS.class.getClassLoader().getResource("g.txt").getPath();
        Graph g = new Graph(filename);
        CC2 cc = new CC2(g);
        System.out.println(cc.count());
        System.out.println(cc.isConnectTo(0, 6));
        System.out.println(cc.isConnectTo(0, 5));
        ArrayList<Integer>[] components = cc.components();
        for (int i = 0; i < components.length; i++) {
            System.out.println(i + ": " + components[i]);
        }
    }
}
